package org.vacoor.nothing.ui.hotkey;

import org.vacoor.nothing.ui.hotkey.impl.linux.JXGrabKeyManager;
import org.vacoor.nothing.ui.hotkey.impl.win.JIntellitypeManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 系统级快捷键
 * <p/>
 * User: Vacoor
 */
public abstract class OSHotKeyManager {

    /**
     * 该方法一般不需要调用, 仅用于内部判断是否支持当前系统
     *
     * @return
     */
    protected abstract boolean supportCurrentOS();

    /**
     * 获取支持当前系统的热键绑定器, 如果不存在返回null
     *
     * @param identifier 绑定器标示符, 一般表示一个功能
     * @return
     */
    public abstract OSHotKeyBinder getOSHotKeyBinder(int identifier);

    /**
     * 销毁并释放资源
     */
    public abstract void destory();

    // --------------------------------------

    private static org.vacoor.nothing.ui.hotkey.OSHotKeyManager currentHotKeyManager;
    private static boolean loaded;   // 是否已经加载过

    public static org.vacoor.nothing.ui.hotkey.OSHotKeyManager getCurrentOSHotKeyManager() {
        if (currentHotKeyManager != null) {
            return currentHotKeyManager;
        }
        synchronized (org.vacoor.nothing.ui.hotkey.OSHotKeyManager.class) {
            if (currentHotKeyManager == null && !loaded) {
                Iterable<org.vacoor.nothing.ui.hotkey.OSHotKeyManager> hotKeyManagers = getHotKeyManagers();
                for (org.vacoor.nothing.ui.hotkey.OSHotKeyManager ohkm : hotKeyManagers) {
                    if (ohkm.supportCurrentOS()) {
                        currentHotKeyManager = ohkm;
                        break;
                    }
                }
                loaded = true;
            }
        }
        return currentHotKeyManager;
    }

    private static Iterable<org.vacoor.nothing.ui.hotkey.OSHotKeyManager> getHotKeyManagers() {
        List<org.vacoor.nothing.ui.hotkey.OSHotKeyManager> providers = new ArrayList<org.vacoor.nothing.ui.hotkey.OSHotKeyManager>();
        providers.add(new JXGrabKeyManager());
        providers.add(new JIntellitypeManager());
        return providers;
//        return getProviders(OSHotKeyManager.class);
    }

    private static <S> Iterable<S> getProviders(Class<S> providerClass) {
        ServiceLoader<S> providers = ServiceLoader.load(providerClass);
        return providers;
    }

    static int identifier = (int) new Date().getTime();

    public synchronized static int nextIdentifier() {
        return ++identifier;
    }
}
